package com.ruoyi.drawing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.utils.BeanCopyUtils;
import com.ruoyi.drawing.api.params.DrawingModelRegionParams;
import com.ruoyi.drawing.api.vo.DrawingModelRegionVO;
import org.springframework.stereotype.Service;
import com.ruoyi.drawing.mapper.DtsDrawingModelRegionMapper;
import com.ruoyi.drawing.domain.DtsDrawingModelRegion;
import com.ruoyi.drawing.service.IDtsDrawingModelRegionService;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 图档中心模型区域Service业务层处理
 *
 * @author ZhangYu
 * @date 2024-04-29
 */
@Service
public class DtsDrawingModelRegionServiceImpl extends ServiceImpl<DtsDrawingModelRegionMapper, DtsDrawingModelRegion> implements IDtsDrawingModelRegionService {

    @Override
    public List<DrawingModelRegionVO> regionTree() {
        List<DtsDrawingModelRegion> dtsDrawingModelRegionList = baseMapper.selectList(new QueryWrapper<>());
        List<DrawingModelRegionVO> newDrawingModelRegionList = BeanCopyUtils.copyList(dtsDrawingModelRegionList, DrawingModelRegionVO.class);
        Map<Long, List<DrawingModelRegionVO>> dtsDrawingModelRegionMap = newDrawingModelRegionList.stream().filter(dmr -> 0L != dmr.getParentId()).collect(Collectors.groupingBy(DrawingModelRegionVO::getParentId));
        return newDrawingModelRegionList.stream().peek(dmr -> dmr.setChildren(dtsDrawingModelRegionMap.get(dmr.getId()))).filter(dmr -> 0L == dmr.getParentId()).collect(Collectors.toList());
    }

    @Override
    public void addDrawingModelRegion(DrawingModelRegionParams drawingModelRegionParams) {
        DtsDrawingModelRegion drawingModelRegion = BeanCopyUtils.copyNewBean(drawingModelRegionParams, DtsDrawingModelRegion.class);
        //获取祖级列表
        String ancestors = getAncestors(drawingModelRegion.getParentId());
        drawingModelRegion.setAncestors(ancestors);
        baseMapper.insert(drawingModelRegion);
    }

    /**
     * 获取祖级列表
     *
     * @param parentId 父id
     * @return 祖级列表
     */
    private String getAncestors(Long parentId) {
        if (0L == parentId) {
            return Constants.LOGIN_SUCCESS_STATUS;
        }
        DtsDrawingModelRegion parentRegion = baseMapper.selectById(parentId);
        return parentRegion.getAncestors() + StrUtil.C_COMMA + parentId;
    }

    @Override
    public void updateDrawingModelRegion(DrawingModelRegionParams drawingModelRegionParams) {
        DtsDrawingModelRegion drawingModelRegion = BeanUtil.copyProperties(drawingModelRegionParams, DtsDrawingModelRegion.class);
        String ancestors = getAncestors(drawingModelRegion.getParentId());
        drawingModelRegion.setAncestors(ancestors);
        baseMapper.updateById(drawingModelRegion);
    }

}
